package com.df.gateway.commandentry;

import com.df.gateway.config.ServiceMappingConfig;
import com.df.gateway.handler.GatewayHttpHandler;
import com.df.gateway.predicate.GatewayHttpPredicate;
import com.df.gateway.predicate.GatewayTcpPredicate;
import com.df.library.net.MultiProtocolServer;
import com.df.library.net.condition.HttpDefaultProtocolPredicate;
import com.df.library.net.condition.IProtocolPredicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CommandEntry implements CommandLineRunner, ApplicationContextAware {

    @Value("${gate-way.port}")
    private int port;

    private ApplicationContext applicationContext;

    @Autowired
    private ServiceMappingConfig serviceMappingConfig;

    private MultiProtocolServer server;

    @Override
    public void run(String... args) throws Exception {
        List<Class<? extends IProtocolPredicate>> conditions = new ArrayList<>();

        //TODO predicate 和 channel handler判断哪些是无状态的(shareable)，无状态的则所有channel都用同一个实例，
        // 防止创建过多对象
        //http协议，用于处理登录，充值回调等消息
        conditions.add(GatewayHttpPredicate.class);
        //自定义Tcp协议，用于处理长连接信息，比如地图移动等消息
        conditions.add(GatewayTcpPredicate.class);

        server = new MultiProtocolServer("gateway-server",port,conditions);
        server.start((s,c)->{
           log.info("多协议服务启动成功！");
        });

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PreDestroy
    public void close(){
        if(server!=null){
            server.stop();
        }
    }
}
